import { RowDataPacket } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import { getLoginUid, responseJson } from "~/server/utils/helper/index";

export default defineEventHandler(async (event) => {
  // 获取用户ID
  let uid = getLoginUid(event);
  
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  const con = getDB();

  try {
    // 查询用户信息
    const [rows] = await con.execute<RowDataPacket[]>(
      "SELECT id, nickname, phone, avatar FROM `users` WHERE `id`=?",
      [uid]
    );
    
    if (Array.isArray(rows) && rows.length > 0) {
      return responseJson(0, "获取成功", {
        uid: rows[0].id,
        nickname: rows[0].nickname,
        phone: rows[0].phone,
        avatar: rows[0].avatar
      });
    } else {
      return responseJson(1, "用户不存在", {});
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    return responseJson(1, "获取用户信息失败", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
